package com.jar.exercise.多线程.死锁代码;

import com.jar.exercise.多线程.TheadTools;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class App2 {


    public static void main(String[] args) {

        final Lock lock0 = new ReentrantLock();
        final Lock lock1 = new ReentrantLock();

        final DeadLockBean deadLockBean0 = new DeadLockBean(lock0, lock1);
        final DeadLockBean deadLockBean1 = new DeadLockBean(lock1, lock0);

        TheadTools.getThread(deadLockBean0::deadLock).start();
        TheadTools.getThread(deadLockBean1::deadLock).start();


    }

}

class DeadLockBean {

    final Lock lock0;
    final Lock lock1;

    public DeadLockBean(Lock lock0,Lock lock1) {
        this.lock0 = lock0;
        this.lock1 = lock1;
    }

    public void deadLock(){

        System.out.println("--- --- --- ---");

        lock0.lock();
        String name0 = Thread.currentThread().getName();
        System.out.println("上锁0：" + name0);

        try {
            Thread.sleep(1_000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        String name1 = Thread.currentThread().getName();
        System.out.println("上锁1：" + name1);
        lock1.lock();

    }

}